package grape.sequence.service.generator.dbbased;

import cn.hutool.core.date.DateUtil;
import grape.common.tools.ToolService;
import grape.sequence.service.generator.mapper.MysqlGeneratorMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.sql.SQLSyntaxErrorException;

/**
 * mysql的数据库实现,默认是该实现
 * Created by yangwei
 * Created at 2020/8/20 19:14
 */
@Component
public class SequenceMysqlGenerator implements ISequenceDatabaseTypeGenerator , ToolService {

    @Autowired
    private MysqlGeneratorMapper mysqlGeneratorMapper;

    @Override
    public boolean support(String databaseType) {
        return isStrEmpty(databaseType) || isEqual("mysql",databaseType);
    }

    @Override
    public SequenceResult nextSeqValue(String suffix, Integer startValue, Integer stepValue) {

        String tableName = tablePrefix + suffix;
        String now = DateUtil.now();

        SequenceResult sequenceResult = new SequenceResult();

        GeneratorInsertPo generatorInsertPo = new GeneratorInsertPo();
        generatorInsertPo.setCreateAt(now);
        generatorInsertPo.setTableName(tableName);
        // 步长支持
        generatorInsertPo.initStepNums(stepValue);
        try {
            mysqlGeneratorMapper.insert(generatorInsertPo);
            sequenceResult.setFirst(false);
        } catch (Exception e) {

            Throwable tempE = null;
            if (e instanceof SQLSyntaxErrorException) {
                tempE = e;
            } else if (e.getCause() instanceof SQLSyntaxErrorException) {
                tempE = e.getCause();
            }
            // 表不存在
            if(tempE != null && e.getMessage().contains(tableName) && e.getMessage().endsWith("doesn't exist")){
                // 异常可能表不存在，创建表
                mysqlGeneratorMapper.createNewTable(tableName);
                if(startValue > 1){
                    // 初始化一条数据
                    GeneratorInsertPo generatorInsertInitStartPo = new GeneratorInsertPo();
                    generatorInsertInitStartPo.setTableName(tableName);
                    generatorInsertInitStartPo.setId(Long.parseLong((startValue - startValue) + ""));
                    mysqlGeneratorMapper.insertFull(generatorInsertInitStartPo);
                }
                mysqlGeneratorMapper.insert(generatorInsertPo);
                sequenceResult.setFirst(true);
            }else{

                throw e;
            }

        }
        sequenceResult.setNextValue(generatorInsertPo.getId().toString());
        return sequenceResult;
    }

    @Override
    public String currentSeqValue(String suffix) {
        String result = null;
        String tableName = tablePrefix + suffix;
        try {
            Long aLong = mysqlGeneratorMapper.maxId(tablePrefix + suffix);
            result = aLong.toString();
        } catch (Exception e) {
            Throwable tempE = null;
            if (e instanceof SQLSyntaxErrorException) {
                tempE = e;
            } else if (e.getCause() instanceof SQLSyntaxErrorException) {
                tempE = e.getCause();
            }
            // 表不存在
            if (tempE != null && e.getMessage().contains(tableName) && e.getMessage().endsWith("doesn't exist")) {
                result = null;
            } else {
                throw e;
            }

        }
        return result;
    }
}
